#-*- coding:utf-8 -*-
import os
import sys
import time
import shutil
from PySide2.QtGui import *
from PySide2.QtCore import *
from PySide2.QtWidgets import *

class CreateShot(QWidget):
    all_shot_info_Signal=Signal(tuple)
    def __init__(self,real_epi_path):
        super(CreateShot,self).__init__()
        self.setStyleSheet(
            'QWidget{background-color:rgb(75,75,75);color:rgb(200,200,200)}QPushButton{background-color:rgb(100,100,100);border:2px;border-radius:2px;padding:3px}QPushButton:hover{color:#f3995e}')


        self.setWindowTitle("创建新镜头")

        self.setMinimumWidth(400)
        self.setMaximumWidth(550)

        #全局变量
        self.shot_path_list=[]#用来记录拖入的镜头的绝对路径
        self.shot_name_list=[]#用来记录拖入的镜头的名称
        self.current_real_epi_path=real_epi_path


        #组件布局
        self.mainLayout=QHBoxLayout()


        self.qSplitter=QSplitter(Qt.Horizontal)

        #左边为镜头栏
        self.left_widget=QWidget()
        self.left_layout=QVBoxLayout()
        self.tip_label=QLabel('拖入镜头')
        self.tip_label.setAlignment(Qt.AlignCenter)
        self.list_widget=QListWidget()
        # self.list_widget.setAcceptDrops(True)
        self.left_layout.addWidget(self.tip_label)
        self.left_layout.addWidget(self.list_widget)
        self.left_widget.setLayout(self.left_layout)

        #右边是信息栏
        self.info_widget=QWidget()
        self.info_layout=QVBoxLayout()


        self.info_label=QLabel('镜头信息')
        self.info_label.setAlignment(Qt.AlignCenter)
        self.name_layout=QHBoxLayout()
        self.name_label=QLabel("制作者  :")
        self.name_edit=QLineEdit()
        self.name_layout.addWidget(self.name_label)
        self.name_layout.addWidget(self.name_edit)

        self.gtime_layout=QHBoxLayout()
        self.gtime_label=QLabel('分配时间:')
        self.gtime_edit=QLineEdit()
        self.gtime_edit.setText('0')
        self.intLimit=QIntValidator(0,99999,self)
        self.gtime_edit.setValidator(self.intLimit)
        self.day_label=QLabel('天')
        self.gtime_layout.addWidget(self.gtime_label)
        self.gtime_layout.addWidget(self.gtime_edit)
        self.gtime_layout.addWidget(self.day_label)

        self.price_layout=QHBoxLayout()
        self.price_label=QLabel('价格    :')
        self.price_edit=QLineEdit()
        self.price_edit.setValidator(self.intLimit)
        self.price_edit.setText('0')
        self.yuan_label=QLabel('元')
        self.price_layout.addWidget(self.price_label)
        self.price_layout.addWidget(self.price_edit)
        self.price_layout.addWidget(self.yuan_label)

        self.info_text=QTextEdit()
        self.info_text.setPlaceholderText('内容描述')

        self.btn_layout=QHBoxLayout()
        self.OK_btn=QPushButton('创建')
        self.OK_btn.clicked.connect(self.__createShot)
        self.NO_btn=QPushButton('取消')
        self.NO_btn.clicked.connect(self.__closeWindow)
        self.btn_layout.addWidget(self.OK_btn)
        self.btn_layout.addWidget(self.NO_btn)

        self.info_layout.addWidget(self.info_label)
        self.info_layout.addLayout(self.name_layout)
        self.info_layout.addLayout(self.gtime_layout)
        self.info_layout.addLayout(self.price_layout)
        self.info_layout.addWidget(self.info_text)
        self.info_layout.addLayout(self.btn_layout)

        self.info_widget.setLayout(self.info_layout)



        self.qSplitter.addWidget(self.left_widget)
        self.qSplitter.addWidget(self.info_widget)



        self.mainLayout.addWidget(self.qSplitter)
        self.setLayout(self.mainLayout)

        self.setAcceptDrops(True)




    # def dragLeaveEvent(self, *args, **kwargs):
    def dragEnterEvent(self,event):
        texts=event.mimeData().text()

        t_list=texts.split('\n')

        temp_path_list=[]
        # temp_show_list=[]

        for i in t_list:
            if i !=[] and i not in self.shot_path_list:
                a=i.replace("file:///",'')
                if self.videoFilter(a):
                    temp_path_list.append(a)
                    allfile=os.path.split(a)[1]
                    # filename=os.path.splitext(allfile)[0]
                    if allfile not in self.shot_name_list:
                        self.shot_name_list.append(allfile)
                        # temp_show_list.append(allfile)#显示不带尾缀的


        print(self.shot_name_list)
        self.shot_path_list=temp_path_list
        print(self.shot_path_list)
        self.list_widget.clear()#需要实时清空已存
        self.list_widget.addItems(self.shot_name_list)


    def videoFilter(self,path):
        '''
        过滤函数，当选中的是视频时
        :param path:
        :return:
        '''
        video_list=['.wmv','.asf','.asx','.rm','.rmvb','.mpg','.mpeg','.mpe','.3gp','.mov','.mp4','.m4v','.avi','.dat','.mkv','.flv','.vob']
        fileType=os.path.splitext(path)[1]
        if fileType in video_list:
            return True
        else:
            return False

    def __createShot(self):
        '''
        创建新镜头,同时发射信号出去更新页面，比较烦的就是，按现在的框架，每次创建镜头就要重新读一遍所有镜头info
        信号格式(self.current_real_epi_path,[shot_name1,shot_name2][{shot_name1:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx}},{shot_name2:{artist:xxx,given_time:xxx,status:xxx,price:xxx,requirement:xxx}}])
        :return:
        '''
        artist=self.name_edit.text() #必须要
        given_time=self.gtime_edit.text()#不一定要
        price=self.price_edit.text()#不一定要
        requirement=self.info_text.toPlainText()#不一定要
        start_day=time.strftime("%Y-%m-%d")
        repeat_shot=''
        current_shot_list=os.listdir(self.current_real_epi_path)#重名判定
        if artist:
            if self.shot_name_list !=[]:#确认有镜头拖入
                for i,g in zip(self.shot_name_list,self.shot_path_list):
                    if os.path.splitext(i)[0] in current_shot_list:
                        repeat_shot+=i+' '
                    else:#当不重复时
                        dir_name=os.path.splitext(i)[0]
                        shot_dir_path=os.path.join(self.current_real_epi_path,dir_name)#当前集数下镜头的目录
                        new_shot_path=os.path.join(shot_dir_path,i)
                        self.__create_sample_project_opinion_reference(shot_dir_path)#创建预设文件目录
                        shutil.copyfile(g, new_shot_path)  # 复制镜头，要在预设文件后
                        self.__createInfo(shot_dir_path,artist,given_time,price,requirement,start_day)
                QMessageBox.information(self, '提示', '创建成功')
                if repeat_shot !='':
                    QMessageBox.information(self, '注意', '{}已经存在'.format(repeat_shot))
                #发射信号给主窗口，刷新数据
                self.__emit()
            else:
                QMessageBox.information(self, '提示', '请拖入镜头')
        else:
            QMessageBox.information(self, '提示', '请录入制作者名称')

        self.close()
    def __create_sample_project_opinion_reference(self,shot_dir_path):
        '''
        给定镜头目录路径，创建配套的小样(Sample)，工程(Project)，意见(Opinion)目录
        :param shot_dir_path: 镜头目录文件夹的绝对路径
        :return:
        '''
        sample_path=os.path.join(shot_dir_path,'sample')
        project_path=os.path.join(shot_dir_path,'project')
        opinion_path=os.path.join(shot_dir_path,'opinion')
        referenc_path=os.path.join(shot_dir_path,'reference')

        if not os.path.exists(sample_path):
            os.makedirs(sample_path)

        if not os.path.exists(project_path):
            os.makedirs(project_path)

        if not os.path.exists(opinion_path):
            os.makedirs(opinion_path)

        if not os.path.exists(referenc_path):
            os.makedirs(referenc_path)

    def __createInfo(self,shot_dir_path,artist,given_time,price,requirement,start_day):
        '''
        创建镜头信息，给信息记录该一批镜头的所有具体内容
        :param shot_dir_path: 创建的镜头目录路径(自身镜头名称，不带尾缀)
        :param artist: 制作者
        :param given_time: 制作日期
        :param price: 价格
        :param requirement: 具体该镜头描述
        param start_day: 制作开始时间
        :return:
        '''
        infoPath=os.path.join(shot_dir_path,'info')
        info={}
        info['artist']=artist
        info['given_time']=given_time
        info['status']=0
        info['price']=price
        info['requirement']=requirement
        info['start_day'] = start_day
        with open(infoPath,'w',encoding='utf-8') as w:
            w.write(str(info))



    def __readInfo(self,info_path):

        info=''
        with open(info_path,'r',encoding='utf-8') as r:
            read=r.read()
            info=eval(read)

        return info




    def __emit(self):
        '''
        发射函数，用来刷新创建镜头后所有镜头信息
        内容包括：当前集数真实路径，镜头名称，镜头info信息
        (self.current_real_epi_path,
        [shot_aaa,shot_bbb],
        [shot_aaa:{'artist': '老张', 'given_time': '12', 'status': 0, 'price': '855', 'requirement': '啊我低洼地挖到的21211额222额饿21'},
        shot_bbb:{'artist': 'Master', 'given_time': '2', 'status': 0, 'price': '855', 'requirement': '啊我低洼地挖到的21211额222额饿21'}])
        :return:
        '''
        shot_list=os.listdir(self.current_real_epi_path)
        if shot_list !=[]:

            shot_info_list=[]
            for i in shot_list:
                shot_info_dict={}
                shot_dir_path=os.path.join(self.current_real_epi_path,i)
                shot_info_path=os.path.join(shot_dir_path,'info')
                shot_info=self.__readInfo(shot_info_path)
                shot_info_dict[i]=shot_info
                shot_info_list.append(shot_info_dict)

            out_tuple=(self.current_real_epi_path,shot_list,shot_info_list)

            self.all_shot_info_Signal.emit(out_tuple)
            # print(out_tuple)
        else:
            out_tuple = (self.current_real_epi_path,shot_list,[])
            self.all_shot_info_Signal.emit(out_tuple)
            # print(out_tuple)




    def __closeWindow(self):
        self.close()

if __name__ == '__main__':
    app=QApplication(sys.argv)
    epi_path=r'F:\PycharmOut\BrickMover\Sample\Projects\X战警\包装\04'
    cs=CreateShot(epi_path)
    cs.show()
    sys.exit(app.exec_())


